package CGLIB动态代理;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/*
* cglib动态代理工具类
* */
public class CglibProxy {

    private Object target;

    public CglibProxy(Object target) {
        this.target = target;
    }

    public Object getProxy(){
        Enhancer enhancer = new Enhancer();
        /*设置类加载器*/
        enhancer.setClassLoader(CglibProxy.class.getClassLoader());
        /*设置被代理对象*/
        enhancer.setSuperclass(target.getClass());
        /*增强功能代码编写位置*/
        MethodInterceptor methodInterceptor = new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                /*方法的前置增强*/
                System.out.println("方法的前置增强~");
                Object invoke = method.invoke(target, objects);
                System.out.println("方法的后置增强~");
                return invoke;
            }
        };
        enhancer.setCallback(methodInterceptor);
        /*生成代理对象并返回*/
        Object o = enhancer.create();
        return o;
    }
}
